<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片试图 搜索和添加区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input
            placeholder="请输入关键字"
            v-model="queryInfo.query"
            clearable
            @clear="getListData"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getListData"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-button type="warning" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
    </el-card>

    <!-- 用户列表 -->
    <el-table :data="userlist" border style="width: 100%">
      <el-table-column type="index" label="序号" width="50"> </el-table-column>
      <el-table-column prop="username" label="姓名"> </el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column prop="role_name" label="角色"></el-table-column>
      <el-table-column prop="mg_state" label="状态">
        <template slot-scope="scope">
          <!-- {{ scope.row }} 打出userlist的{}里面的值 状态开关 change为事件名称 -->
          <el-switch
            v-model="scope.row.mg_state"
            @change="usersStateChange(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="role_name" label="操作">
        <template slot-scope="scope">
          <!-- 修改 、删除按钮 根据scope.row.id修改当前用户信息 -->
          <el-button
            type="success"
            icon="el-icon-edit"
            circle
            @click="editShow(scope.row.id)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="removeUser(scope.row.id)"
          ></el-button>
          <!-- 设置按钮 有提示 enterable切换其他按钮提示出来 -->
          <el-tooltip
            content="设置按钮"
            placement="bottom"
            effect="light"
            :enterable="false"
          >
            <el-button
              type="warning"
              icon="el-icon-setting"
              circle
              @click="setRoles(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域  handleSizeChange 选框选择页 CurrentChange中间选择页 
    current-page当前页面     page-size当前页面显示条数 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 3, 4]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 添加用户弹出框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="addFormReset"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addFormValidation">确 定</el-button>
        <el-button @click="addDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 添加修改弹出框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editVisible"
      width="30%"
      @close="addFormReset"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="editValidateInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 角色权限分配弹出框 -->
    <el-dialog
      title="角色权限分配"
      :visible.sync="setRolesDialogVisible"
      width="30%"
      @close="setRolesDialogClosed"
    >
      <div>
        <p>当前用户: {{ this.userInfo.username }}</p>
        <p>当前角色: {{ this.userInfo.role_name }}</p>
        <p>
          分配新角色:
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer">
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        //合法的邮箱
        return cb();
      }
      cb(new Error("邮箱格式错误"));
    };

    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        //合法的邮箱
        return cb();
      }
      cb(new Error("手机格式错误"));
    };

    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userlist: [],
      total: 0,
      addDialogVisible: false,
      editVisible: false,

      addForm: {
        username: "yehn",
        password: "123456",
        email: "420454377@qq.com",
        mobile: "13450129396",
      },

      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },

      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      userInfo: [],
      setRolesDialogVisible: false,
      selectedRoleId: "",
      rolesList: [],
    };
  },

  created() {
    this.getListData();
  },
  methods: {
    // 获取用户数据
    async getListData() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      // console.log(res.data);
      if (res.meta.status !== 200)
        return this.$message.error("获取不到用户信息");
      this.total = res.data.total;
      this.userlist = res.data.users;
    },

    //选择页面
    handleSizeChange(newpage) {
      // console.log(val);
      this.queryInfo.pagesize = newpage;
      this.getListData();
    },
    handleCurrentChange(newpage) {
      // console.log(val);
      this.queryInfo.pagesize = newpage;
      this.getListData();
    },

    //switch按钮状态方法
    async usersStateChange(scopeRow) {
      //准备将修改后的数据提交到数据库  status 变值之后就提交 因为刷新要继续保存状态
      // console.log(scopeRow); //点击之后 变为 true  然后提交到服务端
      const { data: res } = await this.$http.put(
        //请求路径users/:uId/state/:type
        `users/${scopeRow.id}/state/${scopeRow.mg_state}`
      );
      if (res.meta.status !== 200) {
        scopeRow.mg_state = !scopeRow.mg_state; //开状态自动弹回关状态
        return this.$message.error("状态改变失败");
      }
      this.$message.success("状态改变成功");
      // console.log(res.data.mg_state);
    },
    addFormReset() {
      this.$refs.addFormRef.resetFields();
    },
    addFormValidation() {
      this.$refs.addFormRef.validate(async (validate) => {
        // console.log(validate); //判断全部表格是否全部合法 ref定在form那里
        if (!validate) return;
        const { data: res } = await this.$http.post("users", this.addForm);
        if (res.meta.status !== 201) return this.$message.error("添加失败");
        this.$message.success("添加成功");
        // console.log(res.data);

        this.addDialogVisible = false;

        this.getListData(); //重新渲染当前页面
      });
    },

    //获取当前用户信息
    async editShow(id) {
      // console.log(id); ok
      //usesr/:id  :id 就是参数 以一下方式写
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status != 200) {
        return this.$message.error("查询用户信息失败");
      }
      // console.log(res.data.id);
      this.editForm = res.data;
      this.editVisible = true;
    },
    //取消之后重置为原来的内容
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    //edit表单 点击确定提交预验证
    editValidateInfo() {
      this.$refs.editFormRef.validate(async (validate) => {
        // console.log(validate);
        if (!validate) return;
        //发送修改用户信息的数据请求
        const { data: res } = await this.$http.put(
          "users/" + this.editForm.id,
          {
            email: this.editForm.email, //提交修改参数
            mobile: this.editForm.mobile, //提交修改参数
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("更新用户信息数据失败");
        }
        //关闭对话框
        this.editVisible = false;
        //刷新数据列表
        this.getListData();
        this.$message.success("更新用户信息数据成功");
      });
    },
    //删除用户
    async removeUser(id) {
      //通过下面这一句可以知道这个confirm要挂载到vue的原型上
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      // console.log("确定了删除");
      const { data: res } = await this.$http.delete("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("删除用户失败！");
      }
      this.$message.success("删除成功");
      this.getListData();
    },

    //权限分配setRoles
    async setRoles(scopeRow) {
      this.userInfo = scopeRow; //为下面saveRoleInfo做准备
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      }

      this.rolesList = res.data;
      this.setRolesDialogVisible = true;
      // console.log(this.rolesList);
    },
    async saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error("请选择要分配的角色！");
      }

      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectedRoleId,
        }
      );
      console.log(this.selectedRoleId);
      if (res.meta.status !== 200) {
        return this.$message.error("更新角色失败");
      }
      this.$message.success("更新角色成功");
      this.getListData();
      this.setRolesDialogVisible = false;
    },
    setRolesDialogClosed() {
      this.selectedRoleId = "";
      this.userInfo = "";
    },
  },
};
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
</style>